package org.csu.tank.collision;

import com.almasb.fxgl.app.GameApplication;
import com.almasb.fxgl.dsl.components.EffectComponent;
import com.almasb.fxgl.dsl.components.HealthIntComponent;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.physics.CollisionHandler;
import org.csu.tank.GameType;
import org.csu.tank.TankApp;
import org.csu.tank.client.TankClient;
import org.csu.tank.components.DataComponent;
import org.csu.tank.components.PlayerComponent;
import org.csu.tank.effects.HelmetEffect;

import java.util.concurrent.atomic.AtomicBoolean;

import static com.almasb.fxgl.dsl.FXGL.*;

/**
 * 子弹和玩家碰撞(为了扩展多个玩家,所以这里忽略了来自同盟的子弹,友军不能误伤;同样忽略的代码在产生子弹实体的方法里)
 * 子弹消失,玩家减少生命值
 */
public class BulletPlayerHandler extends CollisionHandler {

      public BulletPlayerHandler() {
            super(GameType.BULLET, GameType.PLAYER);
      }

      protected void onCollisionBegin(Entity bullet, Entity player) {
            AtomicBoolean isCollision= new AtomicBoolean(true);
            bullet.getComponentOptional(DataComponent.class).ifPresent(dataComponent -> {
//                  System.out.println("存储了组件的id" + dataComponent.getId());
                  if (dataComponent.getId() == player.getComponent(PlayerComponent.class).getId()) {
                        System.out.println("id 相同不碰撞");
                        isCollision.set(false);
                  }
            });
            if(isCollision.get()==false)
                  return;
            play("normalBomb.wav");
            if (player.getComponent(EffectComponent.class).hasEffect(HelmetEffect.class)) {
                  bullet.removeFromWorld();
                  return;
            }
            spawn("explode", bullet.getCenter().getX() - 25, bullet.getCenter().getY() - 20);
            bullet.removeFromWorld();
            HealthIntComponent hp = player.getComponent(HealthIntComponent.class);
            hp.damage(1);
//            GameApplication tankApp = getAppCast();
//            if (tankApp instanceof TankApp)
//                  tankApp = (TankApp) tankApp;
//            else
//                  tankApp = (TankClient) tankApp;
            if (hp.isZero()) {
                  if (!getb("gameOver")) {
                        player.removeFromWorld();
                        set("gameOver", true);
                        GameApplication tankApp = getAppCast();
                        if (tankApp instanceof TankApp)
                              getSceneService().pushSubScene(((TankApp) tankApp).failedSceneLazyValue.get());
                        else
                              // 多人对战模式，
                              getSceneService().pushSubScene(((TankClient) tankApp).failedSceneLazyValue.get());
//                        getSceneService().pushSubScene(tankApp.failedSceneLazyValue.get());
                  }
            }
      }
}
